%clc
%clear
function split(inputName, m, n,index,folder) 

%  inputName = '1.jpg'
%  m=8;
%  n=1;
%  index = 1;
%  folder =  sprintf('%dx%d',m,n);

X=imread(inputName);
[row col num] = size(X);
ROB = int32(row/n);
COB = int32(col/m);
Y = zeros(row,col,3);
ImageStruct = zeros(ROB,COB,3);
B2 = zeros(row,col);
B3 = zeros(row,col);
B4 = zeros(row,col);
T2 = zeros(row,col);
T3 = zeros(row,col);
T4 = zeros(row,col);
NOB = 1;
for i = 1 : m
   for j = 1 : n
        a = (i-1)*COB+1;
        b = min(col,COB*i);
        c = (j-1)*ROB+1;
        d = min(row,(ROB*j));
        block = X(c:d,a:b,:);
        %sum(sum(sum(block)))
        [B T] = FSC_v2(block);
        FF = T*B;
        
        Rr = FF(:,1)';
        Rg = FF(:,2)';
        Rb = FF(:,3)';
        RP(:,:,1) = reshape(Rr,ROB,COB);
        RP(:,:,2) = reshape(Rg,ROB,COB);
        RP(:,:,3) = reshape(Rb,ROB,COB);
        Y(c:d,a:b,:) = RP;
        
        
        
        [T2_t,B2_t,T3_t,B3_t,T4_t,B4_t] = otherFields(block,RP);
%         T2(c:d,a:b) = T2_t;
%         T3(c:d,a:b,:) = T3_t;
%         T4(c:d,a:b,:) = T4_t;
%         B2(c:d,a:b) = B2_t;
%         B3(c:d,a:b,:) = B3_t;
%         B4(c:d,a:b,:) = B4_t;
         
        tempOutputName = sprintf('%d_1stField-%d.jpg',index,NOB);
        outputName = sprintf('./%s/%s',folder,tempOutputName);
        imwrite(uint8(RP), outputName);
        
        ImageStruct(:,:,1) = T2_t.*B2_t;
        tempOutputName = sprintf('%d_2ndField-%d.jpg',index,NOB);
        outputName = sprintf('./%s/%s',folder,tempOutputName);
        imwrite(uint8(ImageStruct), outputName);
        ImageStruct(:,:,1) = zeros(ROB,COB);
        
        ImageStruct(:,:,2) = T3_t.*B3_t;
        tempOutputName = sprintf('%d_3rdField-%d.jpg',index,NOB);
        outputName = sprintf('./%s/%s',folder,tempOutputName);
        imwrite(uint8(ImageStruct), outputName);
        ImageStruct(:,:,2) = zeros(ROB,COB);
        
        ImageStruct(:,:,3) = T4_t.*B4_t;
        tempOutputName = sprintf('%d_4thField-%d.jpg',index,NOB);
        outputName = sprintf('./%s/%s',folder,tempOutputName);
        imwrite(uint8(ImageStruct), outputName);
        ImageStruct(:,:,3) = zeros(ROB,COB);
        
        NOB = NOB+1;
   end
end
%imshow(uint8(Y));
%tempOutputName = sprintf('1stField_%d.jpg',index);
%outputName = sprintf('./%s/_%s',folder,tempOutputName);
%imwrite(uint8(Y), outputName);

cover_energy = sum(sum(sum(Y))) / sum(sum(sum(X)))

red = sum(sum(X(:,:,1)))/sum(sum(sum(X)));
green = sum(sum(X(:,:,2)))/sum(sum(sum(X)));
blue = sum(sum(X(:,:,3)))/sum(sum(sum(X)));

txtName = sprintf('result.txt');
fid=fopen(txtName,'a');
fprintf(fid,'%d.jpg|%f|%d*%d|%f|%f|%f\n',index,cover_energy,m,n,red,green,blue);
fclose(fid);

%end